Home:ALL Converter>Leetcode: Remove duplicates from sorted array (Javascript)

Leetcode: Remove duplicates from sorted array (Javascript)

Ask Time:2018-11-22T14:58:17         Author:annieg4123

Json Formatter

Why does my solution work in the console but not on leetcode?

var removeDuplicates = function(nums) {
    let res = [];     
    for(let num of nums) {
        if(res.includes(num) === false) {
            res.push(num);
        }
    }   
    return res.length;
};

Console: screenshot

Leetcode:

let arr = [1, 1, 2]

removeDuplicates(arr) // 3 

Author:annieg4123,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/53425420/leetcode-remove-duplicates-from-sorted-array-javascript
Nitish Narang :

You can try changing includes to indexOf, may be includes is not working in your environment. Also, instead of returning length you should return res.\n\nJust in case you want to try another approach, you can look at Sets like below\n\n\r\n\r\nvar removeDuplicates = function(nums) {\r\n return [...new Set(nums)]\r\n};\r\n\r\nconsole.log(removeDuplicates([1,1,2]))\r\n\r\nconsole.log(removeDuplicates([1,1,2,3]))",
2018-11-22T07:04:59
MBo :

You don't use sortness properly. Algorithmically it is more effective to compare item with previous one, so complexity is O(N). \n\nPerhaps JS has some high-order function like Python groupby to make shorter code, but described method is definitely the best possible from algorithmical point of view.\n\nideone \n\nvar removeDuplicates = function(nums) {\n let res = []; \n let last = NaN\n for(i=0; i<nums.length; i++) {\n if(nums[i] != last) {\n res.push(nums[i]);\n last = nums[i];\n }\n } \n return res.length;\n};\n\nlet arr = [1, 1, 2]\nprint(removeDuplicates(arr)) \n\n>>2\n",
2018-11-22T07:14:36
yy